import { _decorator, Component, instantiate, Node, Prefab, SpriteFrame, color, Sprite } from 'cc';
import { Config } from './config';
import { ItemColor } from './enums';
const { ccclass, property } = _decorator;

@ccclass('nextShape')
export class nextShape extends Component {
    private nextShapes: Node[][] = [][Config.nextCol];//下一个图形颜色列表
    private nextColor: ItemColor;
    private nextItemShape: number[][];

    @property({ type: Prefab })
    private box: Prefab | null = null;

    private colors: SpriteFrame[] = []

    start() {
    }

    update(deltaTime: number) {

    }

    nextItemInit(colors: SpriteFrame[], nextColor: ItemColor, nextItem: number[][]) {
        this.colors = colors;
        this.nextShapes = [];
        this.node.removeAllChildren();

        var a = 0, b = 0;
        for (var i = 0; i < Config.nextRow; i++, b += Config.nextItemHeight) {
            a = 0;
            this.nextShapes.push([]);

            for (var j = 0; j < Config.nextCol; j++, a += Config.nextItemWidth) {
                var nextNode = instantiate(this.box);
                this.node.addChild(nextNode);
                nextNode.setPosition(a, b);
                this.nextShapes[i].push(nextNode);
            }
        }

    }

    //转换下一个图形
    changeNext(nextColor: ItemColor, nextItem: number[][]) {
        this.nextColor = nextColor;
        this.nextItemShape = nextItem;

        this.generateNextShape();
    }

    //渲染下一个图形
    generateNextShape() {
        this.clearAllShape()
        var maxX = 0, maxY = 0;

        this.nextItemShape.forEach(item => {
            maxX = Math.max(maxX, item[0]);
        })

        let tempNext = this.nextShapes;
        this.nextItemShape.forEach(item => {
            var i = item[0] + (maxX < 2 ? 1 : 0), j = item[1] - 2;
            tempNext[i][j].getComponent(Sprite).spriteFrame = this.colors[this.nextColor - 1];
        })
    }

    //清除当前图形
    clearAllShape() {
        for (var i = 0; i < Config.nextRow; i++) {
            for (var j = 0; j < Config.nextCol; j++) {
                this.nextShapes[i][j].getComponent(Sprite).spriteFrame = null;
            }
        }
    }
}


